package com.etc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.etc.dao.FriendsMapper;
import com.etc.entity.Friends;
import com.etc.entity.User;
import com.etc.service.FriendService;

/**
 * 添加好友，删除好友，发送好友请求的业务类
 * 
 * @author 黎嘉华
 *
 */
@Service
public class FriendsServiceImpl implements FriendService {

	/**
	 * 注入FriendsMapper
	 */
	@Autowired
	private FriendsMapper friendsMapper;

	/**
	 * 添加好友
	 */
	@Override
	@Transactional
	public boolean addFriend(Friends friends) {
		// 创建一个Friends的对象
		Friends friends2 = new Friends();

		friends2.setFromuserid(friends.getTouserid());

		friends2.setTouserid(friends.getFromuserid());

		friends2.setRelationstate(1);

		boolean bool = friendsMapper.insertSelective(friends2) > 0;

		boolean bool2 = friendsMapper.handleFriendsReq(friends) > 0;

		if (bool2 && bool) {
			return true;
		}
		return false;
	}

	/**
	 * 添加好友请求
	 */
	@Override
	public boolean sendFriendsReq(Friends friends) {
		// TODO Auto-generated method stub
		return friendsMapper.addFriendsReq(friends) > 0;
	}

	/**
	 * 删除好友
	 */
	@Override
	@Transactional
	public boolean delFriends(Friends recond) {
		// TODO Auto-generated method stub
		// 创建一个Friends的对象
		Friends friends2 = new Friends();

		friends2.setFromuserid(recond.getTouserid());

		friends2.setTouserid(recond.getFromuserid());

		boolean bool = friendsMapper.delFriendsOrReq(friends2) > 0;

		boolean bool2 = friendsMapper.delFriendsOrReq(recond) > 0;

		if (bool2 && bool) {
			return true;
		}
		return false;

	}

	/**
	 * 删除好友请求
	 */
	@Override
	public boolean delFriendsReq(Friends recond) {
		// TODO Auto-generated method stub
		return friendsMapper.delFriendsOrReq(recond) > 0;
	}

	/**
	 * 获取所有添加好友请求
	 */
	@Override
	public List<User> getFriendsReq(Integer userId) {
		// TODO Auto-generated method stub
		return friendsMapper.getFriendsReq(userId);
	}

	/**
	 * 获取所有的好友对
	 */
	@Override
	public List<User> getFriendsUser(Integer userId, String content) {
		// TODO Auto-generated method stub
		List<User> friendsUser = friendsMapper.getFriendsUser(userId);

		List<User> friends = new ArrayList<>();
		for (User user : friendsUser) {
			if (user.getUsername().contains(content) || user.getUserphone().contains(content)) {
				friends.add(user);
			}
		}
		return friends;
	}

	/**
	 * 根据fromuserid和touserid 获取好友请求判断好友请求关系是否存在
	 */
	@Override
	public List<Friends> getFriendByReq(Integer fromuserId, Integer touserId) {
		// TODO Auto-generated method stub
		return friendsMapper.getFriendByReq(fromuserId, touserId);
	}

}
